import { useCallback, useEffect, useState } from 'react';
import { Empty, Image, InfiniteScroll, List } from 'antd-mobile'
import moment from 'moment';
import { InbizIcon, useEvents } from '@inbiz/utils';
import defaultImg from '../../../icons/defaultImg.png';
import { NewsProps } from '../index';
import { getNewsList as getNewsListData, getCounts } from '../../../service';
import '../style.less';
import { getMessage } from '@inbiz/react';

const Summary: React.FC<NewsProps> = (props) => {
    const { showCate, everytimeLoad, fixNewKey, standOut, goToDetail } = props;

    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const [pageIndex, setPageIndex] = useState<number>(1);
    const [configEvents] = useEvents(props.callBackEvents, props.emit)

    const getNewsList = useCallback(async (params: object) => {
        const newParams = (await configEvents.current?.onParams?.(params)) || params;
        const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
        return await configEvents.current?.onData?.(data) || data
    }, []);

    const getStreamData = async (page: number) => {
        try {
            setLoading(true)
            const res: News.NewsList = await getNewsList({
                categoryId: fixNewKey?.map((item: any) => { return item.id }).toString(),
                pageIndex: page,
                pageSize: everytimeLoad?.threshold,
                showNew: standOut?.isStandout,
                numNew: standOut?.threshold || undefined,
            });
            let _ids = res?.ContentList?.map((item) => item?.ID);
            let counts = await getCounts({ entitylds: _ids });
            let _data = res?.ContentList?.map((item) => {
                let _item = counts?.data?.find((item2: { EntityId: string; }) => item2?.EntityId == item?.ID);
                if (_item) {
                    return {
                        ...item,
                        View: _item?.View
                    }
                } else {
                    return item
                }
            });
            if (page == 1) {
                setData(_data);
            } else {
                setData(data?.concat(_data));
            }
            if (res?.Total > res?.PageSize * res?.PageIndex) {
                setHasMore(true);
            } else {
                setHasMore(false);
            }
            setPageIndex(res?.PageIndex);
            setLoading(false)
        } catch (error) {
            console.error(error);
        }
    };

    const loadMore = async () => {
        await getStreamData(pageIndex + 1);
    };

    useEffect(() => {
        getStreamData(1);
    }, [fixNewKey?.length, everytimeLoad, standOut]);

    return (
        <>{data?.length > 0 ? <div className="summary-content">
            <List>
                {data?.map(item => (
                    <div className="summary-list-item" onClick={() => { goToDetail(item) }}>
                        <List.Item
                            key={item.ID}
                            prefix={
                                <Image
                                    src={item?.ImgUrl == '/inbiz/wcm/UploadFile/Plugins/TextList/Content/Images/notfound.png' ? defaultImg : item?.ImgUrl}
                                    style={{ borderRadius: 6 }}
                                    fit='cover'
                                    width={112}
                                    height={63}
                                />
                            }
                            description={item?.Summary}
                        >
                            {showCate ? `【${item?.ContentCategoryName}】${item?.Title}` : `${item?.Title}`}
                            {item?.IsNew && <div style={{ position: 'absolute', left: 0, top: 5 }}><InbizIcon type='icon-NEW' style={{ fontSize: 34 }} /></div>}
                        </List.Item>
                        <div className="summary-other">
                            <div className="summary-other-content">
                                <div>
                                    {item?.Creator?.length > 6 ? item?.Creator?.slice(0, 6) + '...' : item?.Creator}
                                </div>
                                <div>
                                    {item?.View + '浏览'}
                                </div>
                            </div>
                            <div className="summary-other-time">
                                {moment().isSame(new Date(item?.CreateTime), 'year') ? moment(item?.CreateTime).format('MM-DD') : item?.CreateTime}
                            </div>
                        </div>
                    </div>
                ))}
            </List>
            {
                (!loading && data?.length)
                    ?
                    <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
                    : null
            }
        </div> : <Empty
            image={<InbizIcon type="icon-ic-zanwushuju" style={{ fontSize: '50px' }} />}
            description={getMessage('News.noData')}
        />}</>

    )
}

export default Summary;